﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using QLNHK.BLL;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;


namespace QLNHK
{
    public partial class frmBaoCaoTongHop : Form
    {
        private DataSet dsData = new DataSet();
        frmWait frmWaiting;

        public frmBaoCaoTongHop()
        {
            InitializeComponent();
        }
        private void frmBaoCaoTongHop_Load(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                Global.setDataToComboThanhPho(cboThanhPho);
                cboThanhPho.Value = ConfigNHK.Install.ThanhPho;
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }

        private void btnThongKe_Click(object sender, EventArgs e)
        {
            frmWaiting = new frmWait();
            ThreadPool.QueueUserWorkItem(OnProcess);
            frmWaiting.ShowDialog(this);
        }
        private void OnProcess(object o)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    frmWaiting.SetCaption("Vui lòng chờ giây lát");

                    //Load data tại đây
                    this.LoadData(ref frmWaiting);
                    frmWaiting.DialogResult = DialogResult.OK;
                }));
            }
        }
        private void LoadData(ref frmWait frmW)
        {
            try
            {
                DataTable dt = new DataTable("Table1");
                dt.Columns.Add("Col1", typeof(string));
                dt.Columns.Add("Col2", typeof(string));
                dt.Columns.Add("Col3", typeof(string));
                dt.Columns.Add("Col4", typeof(string));
                dt.Columns.Add("Col5", typeof(string));

                Random random = new Random();
                for (int i = 0; i < 100; i++)
                {
                    string[] rowData = new string[5];
                    for (int j = 0; j < 5; j++)
                        rowData[j] = random.Next(1000).ToString();

                    dt.Rows.Add(rowData);
                }

                this.gridDanhSachNhanKhau.DataSource = dt;

                this.gridDanhSachNhanKhau.DisplayLayout.Bands["Table1"].Groups.Clear();
                this.gridDanhSachNhanKhau.DisplayLayout.Bands["Table1"].LevelCount = 3;

                // Get the columns of Table1 band in the UltraGrid.
                ColumnsCollection gridColumns = this.gridDanhSachNhanKhau.DisplayLayout.Bands["Table1"].Columns;

                // Turn on the row layout functionality for Table1 band.
                this.gridDanhSachNhanKhau.DisplayLayout.Bands["Table1"].UseRowLayout = false;

                // Allow the user to only resize width of the columns/labels.
                this.gridDanhSachNhanKhau.DisplayLayout.Bands["Table1"].Override.AllowRowLayoutCellSizing = RowLayoutSizing.Horizontal;
                this.gridDanhSachNhanKhau.DisplayLayout.Bands["Table1"].Override.AllowRowLayoutLabelSizing = RowLayoutSizing.Horizontal;

                UltraGridGroup groupDangKyThuongTru = this.gridDanhSachNhanKhau.DisplayLayout.Bands["Table1"].Groups.Add("DKTT", "HỘ, NHÂN KHẨU ĐĂNG KÝ THƯỜNG TRÚ");
                groupDangKyThuongTru.Columns.Add(gridColumns["Col1"], 0, 0);
                groupDangKyThuongTru.Columns.Add(gridColumns["Col2"], 1, 0);
                groupDangKyThuongTru.Columns.Add(gridColumns["Col3"], 0, 1);
                groupDangKyThuongTru.Columns.Add(gridColumns["Col4"], 1, 1);
                groupDangKyThuongTru.Columns.Add(gridColumns["Col5"], 0, 2);

                // Setup Col1 column.
                //gridColumns["Col1"].RowLayoutColumnInfo.OriginX = 0;
                //gridColumns["Col1"].RowLayoutColumnInfo.OriginY = 0;
                //gridColumns["Col1"].RowLayoutColumnInfo.SpanX = 1;
                //gridColumns["Col1"].RowLayoutColumnInfo.SpanY = 1;
                //// Set the preferred cell size to 200,0 so that it's at least 200 pixel wide.
                //// Height of 0 means that the UltraGrid will calculate one based on the font.
                //gridColumns["Col1"].RowLayoutColumnInfo.PreferredCellSize = new Size(200, 0);
                //// Set the MinimumCellSize to 50,0 to prevent the user from resizing the column
                //// and making it smaller than 50 in width.
                //gridColumns["Col1"].RowLayoutColumnInfo.MinimumCellSize = new Size(50, 0);

                //// Setup Col2 column.
                //gridColumns["Col2"].RowLayoutColumnInfo.OriginX = 1;
                //gridColumns["Col2"].RowLayoutColumnInfo.OriginY = 0;
                //gridColumns["Col2"].RowLayoutColumnInfo.SpanX = 1;
                //gridColumns["Col2"].RowLayoutColumnInfo.SpanY = 1;

                //// Setup Col3 column.
                //gridColumns["Col3"].RowLayoutColumnInfo.OriginX = 0;
                //gridColumns["Col3"].RowLayoutColumnInfo.OriginY = 1;
                //gridColumns["Col3"].RowLayoutColumnInfo.SpanX = 1;
                //gridColumns["Col3"].RowLayoutColumnInfo.SpanY = 1;

                //// Setup Col4 column.
                //gridColumns["Col4"].RowLayoutColumnInfo.OriginX = 1;
                //gridColumns["Col4"].RowLayoutColumnInfo.OriginY = 1;
                //gridColumns["Col4"].RowLayoutColumnInfo.SpanX = 1;
                //gridColumns["Col4"].RowLayoutColumnInfo.SpanY = 1;
                //// Set the preferred cell size to 150,0 so that it's at least 150 pixel wide.
                //// Height of 0 means that the UltraGrid will calculate one based on the font.
                //gridColumns["Col4"].RowLayoutColumnInfo.PreferredCellSize = new Size(150, 0);
                //// Set the MinimumCellSize to 50,0 to prevent the user from resizing the column
                //// and making it smaller than 50 in width.
                //gridColumns["Col4"].RowLayoutColumnInfo.MinimumCellSize = new Size(60, 0);

                //// Setup Col5 column.
                //gridColumns["Col5"].RowLayoutColumnInfo.OriginX = 0;
                //gridColumns["Col5"].RowLayoutColumnInfo.OriginY = 2;
                //// Set the SpanX to Remainder so that it occupies the rest of the horizontal space.
                //gridColumns["Col5"].RowLayoutColumnInfo.SpanX = RowLayoutColumnInfo.Remainder;
                //gridColumns["Col5"].RowLayoutColumnInfo.SpanY = 1;
                //// Set the preferred cell size height to 40.
                //gridColumns["Col5"].RowLayoutColumnInfo.PreferredCellSize = new Size(0, 40);
                //gridColumns["Col5"].CellMultiLine = DefaultableBoolean.True;

                //Load data
                //dsData = BaoCao.DanhSachTongSoHoKhau(System.Convert.ToInt32(cboThanhPho.Value), System.Convert.ToInt32(cboQuanHuyen.Value), System.Convert.ToInt32(cboXaPhuong.Value));
                //gridDanhSachNhanKhau.DataSource = dsData.Tables[0];

                // Declare an object variable.
                //object sumObject;
                //sumObject = dsData.Tables[0].Compute("Sum(SoHoKhau)", "");
                //int tongSoNhanKhau = (sumObject == System.DBNull.Value ? 0 : System.Convert.ToInt32(sumObject));
                //lblTongSo.Text = string.Format("Tổng số hộ khẩu: {0}", tongSoNhanKhau);
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
        }

        private void cboThanhPho_ValueChanged(object sender, EventArgs e)
        {
            if (cboThanhPho.Value != null)
            {
                int cboThanhPhoValue = 0;
                Int32.TryParse(cboThanhPho.Value.ToString(), out cboThanhPhoValue);
                if (cboThanhPhoValue > 0)
                    Global.setDataToComboQuanHuyen(cboQuanHuyen, Convert.ToInt32(cboThanhPho.Value));
            }
        }
        private void cboQuanHuyen_ValueChanged(object sender, EventArgs e)
        {
            if (cboQuanHuyen.Value != null)
            {
                int cboQuanHuyenValue = 0;
                Int32.TryParse(cboQuanHuyen.Value.ToString(), out cboQuanHuyenValue);
                if (cboQuanHuyenValue > 0)
                    Global.setDataToComboXaPhuong(cboXaPhuong, Convert.ToInt32(cboQuanHuyen.Value));
            }
        }

        private void gridDanhSachNhanKhau_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            try
            {
                e.Layout.Override.CellClickAction = CellClickAction.RowSelect;
                e.Layout.Override.HeaderAppearance.TextHAlign = Infragistics.Win.HAlign.Center;
                e.Layout.Override.WrapHeaderText = Infragistics.Win.DefaultableBoolean.True;

                UltraGridBand band = e.Layout.Bands[0];

                //Caption
                band.Columns["STT"].Header.Caption = "STT";
                band.Columns["ThuongTruXaPhuong"].Header.Caption = "Xã/ Phường";
                band.Columns["ThuongTruQuanHuyen"].Header.Caption = "Quận/ Huyện";
                band.Columns["ThuongTruTinhTP"].Header.Caption = "Tỉnh/ Thành phố";
                band.Columns["SoHoKhau"].Header.Caption = "Tổng số hộ khẩu";

                //Set position
                band.Columns["STT"].Header.VisiblePosition = 0;
                band.Columns["ThuongTruTinhTP"].Header.VisiblePosition = 1;
                band.Columns["ThuongTruQuanHuyen"].Header.VisiblePosition = 2;
                band.Columns["ThuongTruXaPhuong"].Header.VisiblePosition = 3;
                band.Columns["SoHoKhau"].Header.VisiblePosition = 4;

                //Format
                band.Columns["STT"].CellAppearance.TextHAlign =
                band.Columns["SoHoKhau"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Center;
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        
        private void btnXuatExcel_Click(object sender, EventArgs e)
        {
            XuatExcel("Tong so ho khau", saveFileDialog1, excelExporter, Infragistics.Excel.WorkbookFormat.Excel97To2003, gridDanhSachNhanKhau);
        }
        private void XuatExcel(
            string fileName,
            SaveFileDialog saveDialog,
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter exporter,
            Infragistics.Excel.WorkbookFormat excelType,
            Infragistics.Win.UltraWinGrid.UltraGrid grid)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                saveDialog.FileName = fileName;
                saveDialog.Filter = "Excel files (*.xls, *.xlxs)|*.xls;*.xlxs";
                if (DialogResult.OK == saveDialog.ShowDialog())
                {
                    if (saveDialog.FileName.Length > 0)
                    {
                        excelExporter.Export(grid, saveDialog.FileName, excelType);

                        if (DialogResult.OK == MessageBox.Show("Bạn có muốn mở tệp tin Excel được xuất ra không?", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                        {
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
    }
}
